<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hadoop3.0入门,">










<meta name="description" content="本文为慕课网《快速入门Hadoop3.0大数据处理》的第七章，主要讲解：直播平台开播数据统计分析实际案例 该课程地址：https://www.imooc.com/learn/1159">
<meta name="keywords" content="Hadoop3.0入门">
<meta property="og:type" content="article">
<meta property="og:title" content="【四】快速入门Hadoop3.0大数据处理——直播平台开播数据统计分析实际案例">
<meta property="og:url" content="https://aiolos123.gitee.io/blog/2019/12/26/hadoop3.0-step-by-step-4/index.html">
<meta property="og:site_name" content="Aiolos">
<meta property="og:description" content="本文为慕课网《快速入门Hadoop3.0大数据处理》的第七章，主要讲解：直播平台开播数据统计分析实际案例 该课程地址：https://www.imooc.com/learn/1159">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191227061220118.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191227061658218.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191228063315996.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191228063432472.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191228063942962.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191228064921404.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191229062356022.jpg">
<meta property="og:updated_time" content="2019-12-28T22:30:00.458Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="【四】快速入门Hadoop3.0大数据处理——直播平台开播数据统计分析实际案例">
<meta name="twitter:description" content="本文为慕课网《快速入门Hadoop3.0大数据处理》的第七章，主要讲解：直播平台开播数据统计分析实际案例 该课程地址：https://www.imooc.com/learn/1159">
<meta name="twitter:image" content="https://aiolos123.gitee.io/blog/images/20191227061220118.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://aiolos123.gitee.io/blog/2019/12/26/hadoop3.0-step-by-step-4/">





  <title>【四】快速入门Hadoop3.0大数据处理——直播平台开播数据统计分析实际案例 | Aiolos</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Aiolos</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">记录我的成长点滴</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://aiolos123.gitee.io/blog/blog/2019/12/26/hadoop3.0-step-by-step-4/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="aiolos">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blog/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Aiolos">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">【四】快速入门Hadoop3.0大数据处理——直播平台开播数据统计分析实际案例</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-12-26T05:53:30+08:00">
                2019-12-26
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/Hadoop/" itemprop="url" rel="index">
                    <span itemprop="name">Hadoop</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>本文为慕课网《快速入门Hadoop3.0大数据处理》的第七章，主要讲解：直播平台开播数据统计分析实际案例</p>
<p>该课程地址：<a href="https://www.imooc.com/learn/1159" target="_blank" rel="noopener">https://www.imooc.com/learn/1159</a></p>
<a id="more"></a>

<p><strong>注意：MapReduce中reduce阶段的v2s的数据结构是类似于[xx,xx,xx,xx]的列表</strong></p>
<h2 id="案例需求分析"><a href="#案例需求分析" class="headerlink" title="案例需求分析"></a>案例需求分析</h2><ol>
<li><p>需求： 运营部门需要针对主播每天的开播数据进行分析，统计出来每天受欢迎程序比较高的一些主播，进而对这些主播分发更多流量，挖掘最大价值。</p>
</li>
<li><p>原始数据格式如下</p>
<blockquote>
<p>每条数据代表主播的一次直播记录，在直播完成后保存</p>
</blockquote>
<figure class="highlight 1c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">	<span class="string">"id"</span>:<span class="string">"3483343"</span>, <span class="comment">//视频id</span></span><br><span class="line">	<span class="string">"uid"</span>:<span class="string">"434545"</span>, <span class="comment">//主播id</span></span><br><span class="line">	<span class="string">"nickname"</span>:<span class="string">"jack"</span>, <span class="comment">//主播昵称</span></span><br><span class="line">	<span class="string">"gold"</span>:<span class="number">434</span>, <span class="comment">//本次直播收获金币数</span></span><br><span class="line">    <span class="string">"watchnumpv"</span>:<span class="number">4565</span>, <span class="comment">//本次直播被浏览的次数(pv)</span></span><br><span class="line">    <span class="string">"watchnumuv"</span>:<span class="number">656</span>, <span class="comment">//本次直播的独立访问量(uv)</span></span><br><span class="line">    <span class="string">"hots"</span>:<span class="number">2134</span>, <span class="comment">//本次直播被点赞次数</span></span><br><span class="line">    <span class="string">"nofollower"</span>:<span class="number">655</span>, <span class="comment">//本次直播期间取关人数</span></span><br><span class="line">    <span class="string">"looktime"</span>:<span class="number">8543</span>, <span class="comment">//所有人观看本次直播的总时长</span></span><br><span class="line">    <span class="string">"smlook"</span>:<span class="number">531</span>, <span class="comment">//进入该直播间观看时间大于20s的总人数</span></span><br><span class="line">    <span class="string">"follower"</span>:<span class="number">6432</span>, <span class="comment">//本次直播期间关注人数</span></span><br><span class="line">    <span class="string">"gifter"</span>:<span class="number">632</span>, <span class="comment">//本次直播的送礼人数(uv)</span></span><br><span class="line">    <span class="string">"length"</span>:<span class="number">1324</span>, <span class="comment">//本次直播的时长</span></span><br><span class="line">    <span class="string">"area"</span>:<span class="string">"A_US"</span>, <span class="comment">//主播所属地区</span></span><br><span class="line">    <span class="string">"rating"</span>:<span class="string">"A"</span>, <span class="comment">//视频评级</span></span><br><span class="line">    <span class="string">"exp"</span>:<span class="number">2315</span>, <span class="comment">//本次直播获取的经验值</span></span><br><span class="line">    <span class="string">"type"</span>:<span class="string">"video_rating"</span> <span class="comment">//当前数据的类型</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
</ol>
<h2 id="原始数据清洗代码实现"><a href="#原始数据清洗代码实现" class="headerlink" title="原始数据清洗代码实现"></a>原始数据清洗代码实现</h2><blockquote>
<p>由于原始数据是通过日志方式进行记录的，在使用日志采集工具(如Flume)采集到HDFS之后，还需要对数据进行清洗过滤，丢弃缺失字段的数据，针对异常字段值进行标准化处理</p>
</blockquote>
<p>原始数据清洗实现代码如下：</p>
<ol>
<li><p>原始数据清洗需求说明</p>
<figure class="highlight markdown"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"><span class="bullet"> *  </span>数据清洗作业</span><br><span class="line"><span class="bullet"> *  </span>需求：</span><br><span class="line"><span class="bullet"> *  </span>1. 从原始数据(JSON格式)中过滤出需要的字段</span><br><span class="line"><span class="bullet"> *  </span>主播ID(uid)、金币数量(gold)、总观看PV(watchnumpv)、粉丝关注数量(follower)、视频总开播时长(length)</span><br><span class="line"><span class="bullet"> *  </span>2. 针对核心字段进行异常值判断</span><br><span class="line"><span class="bullet"> *  </span>金币数量、总观看PV、粉丝关注数量、视频总开播时长</span><br><span class="line"><span class="bullet"> *  </span>以上四个字段正常情况下都不应该是负值，也不应该缺失，</span><br><span class="line"><span class="bullet"> *  </span>如果这些字段值为负值，则认为是异常数据，直接丢弃；</span><br><span class="line"><span class="bullet"> *  </span>如果这些字段值个别有缺失，则认为字段的值为0即可。</span><br><span class="line"> *</span><br><span class="line"><span class="bullet"> *  </span>分析：</span><br><span class="line"><span class="bullet"> *  </span>1. 由于原始数据是json格式，所以可以使用fastjson对原始数据进行解析，获取指定字段的内容；</span><br><span class="line"><span class="bullet"> *  </span>2. 然后对获取到的数据进行异常值判断，只保留满足条件的数据即可</span><br><span class="line"><span class="bullet"> *  </span>3. 由于不需要聚合过程，只是一个简单的过滤操作，所以只需要map阶段即可，reduce阶段不需要。</span><br><span class="line"><span class="bullet"> *  </span>4. 其中map阶段的<span class="xml"><span class="tag">&lt;<span class="name">k1,v1</span>&gt;</span></span>的数据类型是固定的：<span class="xml"><span class="tag">&lt;<span class="name">LongWritable,</span> <span class="attr">Text</span>&gt;</span></span></span><br><span class="line"><span class="bullet"> *      </span><span class="xml"><span class="tag">&lt;<span class="name">k2,v2</span>&gt;</span></span>的数据类型为：<span class="xml"><span class="tag">&lt;<span class="name">Text,</span> <span class="attr">Text</span>&gt;</span></span>,其中k2存储主播ID，v2存储四个核心字段的值，多个字段中间用\t分割</span><br><span class="line"> */</span><br></pre></td></tr></table></figure>
</li>
<li><p>创建数据清洗Map类</p>
<figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> com.alibaba.fastjson.JSON;</span><br><span class="line"><span class="keyword">import</span> com.alibaba.fastjson.JSONObject;</span><br><span class="line"><span class="keyword">import</span> org.apache.hadoop.io.LongWritable;</span><br><span class="line"><span class="keyword">import</span> org.apache.hadoop.io.Text;</span><br><span class="line"><span class="keyword">import</span> org.apache.hadoop.mapreduce.Mapper;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"></span><br><span class="line"><span class="comment"><span class="markdown">/**</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet"> * </span>自定义Map类，在里面实现具体的数据清洗逻辑</span></span></span><br><span class="line"><span class="comment"><span class="markdown"> */</span></span></span><br><span class="line">public <span class="class"><span class="keyword">class</span> <span class="title">DataCleanMapper</span> <span class="keyword">extends</span> <span class="title">Mapper</span>&lt;<span class="title">LongWritable</span>, <span class="title">Text</span>, <span class="title">Text</span>, <span class="title">Text</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment"><span class="markdown">/**</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>map方法的作用：</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>1. 从原始数据(JSON格式)中过滤出需要的字段</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     *    </span>主播ID(uid)、金币数量(gold)、总观看PV(watchnumpv)、</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     *    </span>粉丝关注数量(follower)、视频总开播时长(length)</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>2. 针对核心字段进行异常值判断</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>@param k1</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>@param v1</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>@param context</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>@throws IOException</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>@throws InterruptedException</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="code">     */</span></span></span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    protected <span class="keyword">void</span> map(LongWritable k1, Text v1, Context context) throws IOException, InterruptedException &#123;</span><br><span class="line">        <span class="comment">//1. 获取每一行内容</span></span><br><span class="line">        <span class="built_in">String</span> line = v1.toString();</span><br><span class="line">        <span class="comment">//2. 解析JSON：把json字符串数据转成json对象</span></span><br><span class="line">        JSONObject jsonObject = JSON.parseObject(line);</span><br><span class="line">        <span class="comment">//3. 从json对象中获取需要的字段信息[注意：在获取数值时建议使用getIntValue，如果字段缺失则返回0]</span></span><br><span class="line">        <span class="built_in">String</span> uid = jsonObject.getString(<span class="string">"uid"</span>);</span><br><span class="line">        <span class="built_in">int</span> gold = jsonObject.getIntValue(<span class="string">"gold"</span>);</span><br><span class="line">        <span class="built_in">int</span> watchnumpv = jsonObject.getIntValue(<span class="string">"watchnumpv"</span>);</span><br><span class="line">        <span class="built_in">int</span> follower = jsonObject.getIntValue(<span class="string">"follower"</span>);</span><br><span class="line">        <span class="built_in">int</span> length = jsonObject.getIntValue(<span class="string">"length"</span>);</span><br><span class="line">        <span class="comment">//4. 过滤掉异常数据</span></span><br><span class="line">        <span class="keyword">if</span>(gold &gt;=<span class="number">0</span> &amp;&amp; watchnumpv &gt;=<span class="number">0</span> &amp;&amp; follower &gt;=<span class="number">0</span> &amp;&amp; length &gt;= <span class="number">0</span>)&#123;</span><br><span class="line">            <span class="comment">//5. 封装k2, v2</span></span><br><span class="line">            Text k2 = <span class="keyword">new</span> Text();</span><br><span class="line">            k2.<span class="keyword">set</span>(uid);</span><br><span class="line">            Text v2 = <span class="keyword">new</span> Text();</span><br><span class="line">            v2.<span class="keyword">set</span>(gold+<span class="string">"\t"</span>+watchnumpv+<span class="string">"\t"</span>+follower+<span class="string">"\t"</span>+length);</span><br><span class="line">            context.write(k2, v2);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>创建数据清洗Job类(需禁用Reduce，因清洗数据无需使用Reduce阶段)</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> org.apache.hadoop.conf.Configuration;</span><br><span class="line"><span class="keyword">import</span> org.apache.hadoop.fs.Path;</span><br><span class="line"><span class="keyword">import</span> org.apache.hadoop.io.Text;</span><br><span class="line"><span class="keyword">import</span> org.apache.hadoop.mapreduce.Job;</span><br><span class="line"><span class="keyword">import</span> org.apache.hadoop.mapreduce.lib.input.FileInputFormat;</span><br><span class="line"><span class="keyword">import</span> org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DataCleanJob</span> </span>&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> void main(<span class="type">String</span>[] args) &#123;</span><br><span class="line">        <span class="comment">//组装job，代码都是类似的</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span>(args.length != <span class="number">2</span>)&#123;</span><br><span class="line">            <span class="type">System</span>.out.<span class="built_in">println</span>(<span class="string">"参数不足，需要接收HDFS的输入路径和输出路径两个参数"</span>);</span><br><span class="line">            <span class="comment">//程序退出</span></span><br><span class="line">            <span class="type">System</span>.exit(<span class="number">100</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">// 1. job需要的配置参数</span></span><br><span class="line">            <span class="type">Configuration</span> conf = new <span class="type">Configuration</span>();</span><br><span class="line">            <span class="comment">// 2. 创建一个job</span></span><br><span class="line">            <span class="type">Job</span> job = <span class="type">Job</span>.getInstance(conf);</span><br><span class="line"></span><br><span class="line">            <span class="comment">// 指定当前类</span></span><br><span class="line">            <span class="comment">// 注意：这一行必须设置，否则在集群中执行时找不到WordCountJob这个类</span></span><br><span class="line">            job.setJarByClass(<span class="type">DataCleanJob</span>.<span class="keyword">class</span>);</span><br><span class="line"></span><br><span class="line">            <span class="comment">// 3. 指定输入的HDFS路径(可以是文件，也可以是路径)</span></span><br><span class="line">            <span class="type">FileInputFormat</span>.setInputPaths(job, new <span class="type">Path</span>(args[<span class="number">0</span>]));</span><br><span class="line">            <span class="comment">// 4. 指定输出的HDFS路径(只能指定一个不存在的目录，如果该目录存在，则程序会报错)</span></span><br><span class="line">            <span class="type">FileOutputFormat</span>.setOutputPath(job, new <span class="type">Path</span>(args[<span class="number">1</span>]));</span><br><span class="line"></span><br><span class="line">            <span class="comment">// 5. 指定map相关的代码</span></span><br><span class="line">            job.setMapperClass(<span class="type">DataCleanMapper</span>.<span class="keyword">class</span>);</span><br><span class="line">            <span class="comment">// 指定(map的输出)k2的类型</span></span><br><span class="line">            job.setMapOutputKeyClass(<span class="type">Text</span>.<span class="keyword">class</span>);</span><br><span class="line">            <span class="comment">// 指定(map的输出)v2的类型</span></span><br><span class="line">            job.setMapOutputValueClass(<span class="type">Text</span>.<span class="keyword">class</span>);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        &#125; <span class="keyword">catch</span> (<span class="type">Exception</span> e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>打包上传到服务器[注意：需上传xxxx-jar-with-dependencies.jar的版本，因需要使用其中的依赖(fastjson)]</p>
</li>
<li><p>上传原始数据到HDFS上</p>
<figure class="highlight haskell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="title">hdfs</span> dfs -mkdir -p /<span class="class"><span class="keyword">data</span>/videoinfo/20191227</span></span><br><span class="line"><span class="title">hdfs</span> dfs -put video_rating.log /<span class="class"><span class="keyword">data</span>/videoinfo/20191227</span></span><br></pre></td></tr></table></figure>

</li>
</ol>
<p><img src="/blog/images/20191227061220118.jpg" alt="上传原始数据到HDFS上"></p>
<ol start="6">
<li>提交任务执行程序<br><img src="/blog/images/20191227061658218.jpg" alt="提交任务执行程序"></li>
</ol>
<h2 id="数据统计代码实现–基于主播维度的四个指标"><a href="#数据统计代码实现–基于主播维度的四个指标" class="headerlink" title="数据统计代码实现–基于主播维度的四个指标"></a>数据统计代码实现–基于主播维度的四个指标</h2><ol>
<li><p>需求：基于主播进行统计，统计每个主播在当天收到的总金币数量，总观看pv，总粉丝关注量，总视频开播时长</p>
</li>
<li><p>分析：自定义Writable————由于原始数据中涉及到多个需要统计的字段，所以可以把这几个字段统一记录在一个自定义数据类型中，方便使用</p>
<blockquote>
<p>a. 为了方便统计主播的指标数据，最好是把这些字段整合到一个对象中，这样维护起来比较方便，这样就需要自定义Writable对象了<br>b. 由于在这里需要以主播维度进行数据的聚合，所以需要以主播ID作为key进行聚合统计<br>c. 所以map阶段的&lt;k2,v2&gt;为 &lt;Text,自定义Writable&gt;<br>d. 由于需要聚合，所以Reduce阶段也需要有</p>
</blockquote>
</li>
<li><p>自定义Writable的代码实现</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> org.apache.hadoop.io.Writable;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.DataInput;</span><br><span class="line"><span class="keyword">import</span> java.io.DataOutput;</span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 自定义Hadoop数据类型</span></span><br><span class="line"><span class="comment"> * 主要是为了保存主播相关的核心字段，方便后期进行累加操作</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">VideoInfoWritable</span> <span class="keyword">implements</span> <span class="title">Writable</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//自定义Hadoop数据类型中需要保存的数据</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">long</span> gold;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">long</span> watchnumpv;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">long</span> follower;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">long</span> length;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">write</span><span class="params">(DataOutput dataOutput)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        dataOutput.writeLong(<span class="keyword">this</span>.gold);</span><br><span class="line">        dataOutput.writeLong(<span class="keyword">this</span>.watchnumpv);</span><br><span class="line">        dataOutput.writeLong(<span class="keyword">this</span>.follower);</span><br><span class="line">        dataOutput.writeLong(<span class="keyword">this</span>.length);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">readFields</span><span class="params">(DataInput dataInput)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.gold = dataInput.readLong();</span><br><span class="line">        <span class="keyword">this</span>.watchnumpv = dataInput.readLong();</span><br><span class="line">        <span class="keyword">this</span>.follower = dataInput.readLong();</span><br><span class="line">        <span class="keyword">this</span>.length = dataInput.readLong();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">set</span><span class="params">(<span class="keyword">long</span> gold, <span class="keyword">long</span> watchnumpv, <span class="keyword">long</span> follower, <span class="keyword">long</span> length)</span></span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.gold = gold;</span><br><span class="line">        <span class="keyword">this</span>.watchnumpv = watchnumpv;</span><br><span class="line">        <span class="keyword">this</span>.follower = follower;</span><br><span class="line">        <span class="keyword">this</span>.length = length;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> gold+<span class="string">"\t"</span>+watchnumpv+<span class="string">"\t"</span>+follower+<span class="string">"\t"</span>+length;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">long</span> <span class="title">getGold</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> gold;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">long</span> <span class="title">getWatchnumpv</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> watchnumpv;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">long</span> <span class="title">getFollower</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> follower;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">long</span> <span class="title">getLength</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> length;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>自定义Map的代码实现</p>
<figure class="highlight processing"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 实现自定义Map类，在这里实现核心字段的拼装</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> class DataStatisMap extends Mapper&lt;LongWritable, Text, Text, VideoInfoWritable&gt; &#123;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="built_in">map</span>(LongWritable k1, Text v1, Context context) <span class="keyword">throws</span> IOException, InterruptedException &#123;</span><br><span class="line">        <span class="comment">//1. 读取清洗之后的每一行数据</span></span><br><span class="line">        <span class="keyword">String</span> <span class="built_in">line</span> = k1.toString();</span><br><span class="line">        <span class="comment">//2. 使用\t 对数据进行切割</span></span><br><span class="line">        <span class="keyword">String</span>[] fields = <span class="built_in">line</span>.<span class="built_in">split</span>(<span class="string">"\t"</span>);</span><br><span class="line">        <span class="keyword">String</span> uid = fields[<span class="number">0</span>];</span><br><span class="line">        <span class="keyword">long</span> gold = Long.parseLong(fields[<span class="number">1</span>]);</span><br><span class="line">        <span class="keyword">long</span> watchnumpv = Long.parseLong(fields[<span class="number">2</span>]);</span><br><span class="line">        <span class="keyword">long</span> follower = Long.parseLong(fields[<span class="number">3</span>]);</span><br><span class="line">        <span class="keyword">long</span> length = Long.parseLong(fields[<span class="number">4</span>]);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//组装k2, v2</span></span><br><span class="line">        Text k2 = <span class="keyword">new</span> Text();</span><br><span class="line">        k2.<span class="built_in">set</span>(uid);</span><br><span class="line">        VideoInfoWritable v2 = <span class="keyword">new</span> VideoInfoWritable();</span><br><span class="line">        v2.<span class="built_in">set</span>(gold,watchnumpv,follower,length);</span><br><span class="line"></span><br><span class="line">        context.write(k2, v2);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>自定义Reduce的代码实现</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">public <span class="class"><span class="keyword">class</span> <span class="title">DataStatisReduce</span> <span class="keyword">extends</span> <span class="title">Reducer&lt;Text</span>, <span class="title">VideoInfoWritable</span>, <span class="title">Text</span>, <span class="title">VideoInfoWritable&gt;</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> void reduce(<span class="type">Text</span> k2, <span class="type">Iterable</span>&lt;<span class="type">VideoInfoWritable</span>&gt; v2s, <span class="type">Context</span> context) <span class="keyword">throws</span> <span class="type">IOException</span>, <span class="type">InterruptedException</span> &#123;</span><br><span class="line">        <span class="comment">// 1. 从v2s中把相同key的value取出来，进行累加求和</span></span><br><span class="line">        long goldsum = <span class="number">0</span>;</span><br><span class="line">        long watchnumpvsum = <span class="number">0</span>;</span><br><span class="line">        long followersum = <span class="number">0</span>;</span><br><span class="line">        long lengthsum = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="type">VideoInfoWritable</span> v2:v2s) &#123;</span><br><span class="line">            goldsum += v2.getGold();</span><br><span class="line">            watchnumpvsum += v2.getWatchnumpv();</span><br><span class="line">            followersum += v2.getFollower();</span><br><span class="line">            lengthsum += v2.getLength();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//2. 封装k3,v3</span></span><br><span class="line">        <span class="type">Text</span> k3 = k2;</span><br><span class="line">        <span class="type">VideoInfoWritable</span> v3 = <span class="keyword">new</span> <span class="type">VideoInfoWritable</span>();</span><br><span class="line">        v3.set(goldsum,watchnumpvsum,followersum,lengthsum);</span><br><span class="line"></span><br><span class="line">        context.write(k3, v3);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>Job的代码实现</p>
<figure class="highlight cos"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line">public <span class="keyword">class</span> DataStatisJob &#123;</span><br><span class="line"></span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        <span class="keyword">if</span>(args.length != <span class="number">2</span>)&#123;</span><br><span class="line">            System.out.println(<span class="string">"参数不足，需要接收HDFS的输入路径和输出路径两个参数"</span>)<span class="comment">;</span></span><br><span class="line">            <span class="comment">//程序退出</span></span><br><span class="line">            System.exit(<span class="number">100</span>)<span class="comment">;</span></span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">// 1. job需要的配置参数</span></span><br><span class="line">            Configuration conf = <span class="keyword">new</span> Configuration()<span class="comment">;</span></span><br><span class="line">            <span class="comment">// 2. 创建一个job</span></span><br><span class="line">            <span class="keyword">Job</span> <span class="keyword">job</span> = <span class="keyword">Job</span>.getInstance(conf)<span class="comment">;</span></span><br><span class="line"></span><br><span class="line">            <span class="comment">// 指定当前类</span></span><br><span class="line">            <span class="comment">// 注意：这一行必须设置，否则在集群中执行时找不到DataStatisJob这个类</span></span><br><span class="line">            <span class="keyword">job</span>.setJarByClass(DataStatisJob.<span class="keyword">class</span>)<span class="comment">;</span></span><br><span class="line"></span><br><span class="line">            <span class="comment">// 3. 指定输入的HDFS路径(可以是文件，也可以是路径)</span></span><br><span class="line">            FileInputFormat.setInputPaths(<span class="keyword">job</span>, <span class="keyword">new</span> Path(args[<span class="number">0</span>]))<span class="comment">;</span></span><br><span class="line">            <span class="comment">// 4. 指定输出的HDFS路径(只能指定一个不存在的目录，如果该目录存在，则程序会报错)</span></span><br><span class="line">            FileOutputFormat.setOutputPath(<span class="keyword">job</span>, <span class="keyword">new</span> Path(args[<span class="number">1</span>]))<span class="comment">;</span></span><br><span class="line"></span><br><span class="line">            <span class="comment">// 5. 指定map相关的代码</span></span><br><span class="line">            <span class="keyword">job</span>.setMapperClass(DataStatisMap.<span class="keyword">class</span>)<span class="comment">;</span></span><br><span class="line">            <span class="comment">// 指定(map的输出)k2的类型</span></span><br><span class="line">            <span class="keyword">job</span>.setMapOutputKeyClass(Text.<span class="keyword">class</span>)<span class="comment">;</span></span><br><span class="line">            <span class="comment">// 指定(map的输出)v2的类型</span></span><br><span class="line">            <span class="keyword">job</span>.setMapOutputValueClass(VideoInfoWritable.<span class="keyword">class</span>)<span class="comment">;</span></span><br><span class="line"></span><br><span class="line">            <span class="comment">// 6. 指定reduce相关的代码</span></span><br><span class="line">            <span class="keyword">job</span>.setReducerClass(DataStatisReduce.<span class="keyword">class</span>)<span class="comment">;</span></span><br><span class="line">            <span class="keyword">job</span>.setOutputKeyClass(Text.<span class="keyword">class</span>)<span class="comment">;</span></span><br><span class="line">            <span class="keyword">job</span>.setOutputValueClass(VideoInfoWritable.<span class="keyword">class</span>)<span class="comment">;</span></span><br><span class="line"></span><br><span class="line">            <span class="comment">// 7. 提交job</span></span><br><span class="line">            <span class="keyword">job</span>.waitForCompletion(true)<span class="comment">;</span></span><br><span class="line"></span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace()<span class="comment">;</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
</ol>
<h2 id="数据统计代码实现–基于主播的TOPN计算"><a href="#数据统计代码实现–基于主播的TOPN计算" class="headerlink" title="数据统计代码实现–基于主播的TOPN计算"></a>数据统计代码实现–基于主播的TOPN计算</h2><ol>
<li><p>需求：统计每天开播时长最长的前10名主播及对应的开播时长</p>
</li>
<li><p>分析</p>
<blockquote>
<p> a. 为了统计每天开播最长的前10名主播信息，需要在map阶段获取数据中每个主播的id和直播时长<br>b. 所以map阶段的&lt;k1,v1&gt;的数据类型为&lt;Text, LongWritable&gt;,数值分别为主播id和直播时长<br>c. 在Reduce阶段对相同主播的直播时长机芯累加求和，把这些数据存储到一个临时的map集合中(用于排序求TOPN)<br>d. 在Reduce阶段的cleanup()方法中(它在reduce()方法执行完后执行一次)，对这个临时的map集合中的数据根据直播时长进行排序<br>e. 在cleanup()函数的最后，把直播时长最长的前10名主播的信息写出到HDFS文件中</p>
</blockquote>
</li>
<li><p>自定义Map的代码实现</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 自定义map类，实现核心字段的拼装</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">public <span class="class"><span class="keyword">class</span> <span class="title">DataTopNMap</span> <span class="keyword">extends</span> <span class="title">Mapper&lt;LongWritable</span>, <span class="title">Text</span>, <span class="title">Text</span>, <span class="title">LongWritable&gt;</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> void map(<span class="type">LongWritable</span> k1, <span class="type">Text</span> v1, <span class="type">Context</span> context) <span class="keyword">throws</span> <span class="type">IOException</span>, <span class="type">InterruptedException</span> &#123;</span><br><span class="line">        <span class="comment">//1. 读取清洗之后的每一行数据</span></span><br><span class="line">        <span class="type">String</span> line = k1.toString();</span><br><span class="line">        <span class="comment">//2. 获取主播id和直播时长的数据</span></span><br><span class="line">        <span class="type">String</span>[] fields = line.split(<span class="string">"\t"</span>);</span><br><span class="line">        <span class="type">String</span> uid = fields[<span class="number">0</span>];</span><br><span class="line">        long length = <span class="type">Long</span>.parseLong(fields[<span class="number">4</span>]);</span><br><span class="line">        <span class="comment">//3. 封装k2, v2</span></span><br><span class="line">        <span class="type">Text</span> k2 = <span class="keyword">new</span> <span class="type">Text</span>();</span><br><span class="line">        k2.set(uid);</span><br><span class="line">        <span class="type">LongWritable</span> v2 = <span class="keyword">new</span> <span class="type">LongWritable</span>();</span><br><span class="line">        v2.set(length);</span><br><span class="line"></span><br><span class="line">        context.write(k2, v2);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>自定义Reduce的代码实现</p>
<figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"><span class="markdown">/**</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet"> * </span>自定义reduce类，</span></span></span><br><span class="line"><span class="comment"><span class="markdown"> */</span></span></span><br><span class="line">public <span class="class"><span class="keyword">class</span> <span class="title">DataTopNReduce</span> <span class="keyword">extends</span> <span class="title">Reducer</span>&lt;<span class="title">Text</span>, <span class="title">LongWritable</span>, <span class="title">Text</span>, <span class="title">LongWritable</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//保存所有主播的id和直播时长数据</span></span><br><span class="line">    HashMap&lt;<span class="built_in">String</span>, Long&gt; map = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line"></span><br><span class="line">    <span class="comment"><span class="markdown">/**</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>每一个主播(即每一个k2)调用一次该方法</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>@param k2</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>@param v2s</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>@param context</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>@throws IOException</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>@throws InterruptedException</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="code">     */</span></span></span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    protected <span class="keyword">void</span> reduce(Text k2, <span class="built_in">Iterable</span>&lt;LongWritable&gt; v2s, Context context) throws IOException, InterruptedException &#123;</span><br><span class="line">        long lengthSum = <span class="number">0</span>L;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (LongWritable v2:v2s) &#123;</span><br><span class="line">            lengthSum += v2.<span class="keyword">get</span>();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        map.put(k2.toString(), lengthSum);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//在任务初始化时执行一次，仅执行一次，一般在里面做一些初始化资源链接的动作，如链接数据库、Redis等</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    protected <span class="keyword">void</span> setup(Context context) throws IOException, InterruptedException &#123;</span><br><span class="line">        <span class="keyword">super</span>.setup(context);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//在任务初始化时执行一次，仅执行一次，一般在里面做一些关闭资源链接的动作，</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    protected <span class="keyword">void</span> cleanup(Context context) throws IOException, InterruptedException &#123;</span><br><span class="line">        <span class="comment">//从配置类中获取dt参数</span></span><br><span class="line">        Configuration conf = context.getConfiguration();</span><br><span class="line">        <span class="built_in">String</span> dt = conf.<span class="keyword">get</span>(<span class="string">"dt"</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//1. 根据map中的value进行排序</span></span><br><span class="line">        <span class="built_in">Map</span>&lt;<span class="built_in">String</span>, Long&gt; sortMap = MapUtils.sortValue(map);</span><br><span class="line">        <span class="comment">//2. 从map中取前10条数据</span></span><br><span class="line">        <span class="built_in">Set</span>&lt;<span class="built_in">Map</span>.Entry&lt;<span class="built_in">String</span>, Long&gt;&gt; entries = sortMap.entrySet();</span><br><span class="line">        <span class="built_in">Iterator</span>&lt;<span class="built_in">Map</span>.Entry&lt;<span class="built_in">String</span>, Long&gt;&gt; iterator = entries.iterator();</span><br><span class="line">        <span class="built_in">int</span> count = <span class="number">1</span>;</span><br><span class="line">        <span class="keyword">while</span> (count &lt;= <span class="number">10</span> &amp;&amp; iterator.hasNext())&#123;</span><br><span class="line">            <span class="built_in">Map</span>.Entry&lt;<span class="built_in">String</span>, Long&gt; entry = iterator.next();</span><br><span class="line">            <span class="built_in">String</span> key = entry.getKey();</span><br><span class="line">            Long value = entry.getValue();</span><br><span class="line">            <span class="comment">//3. 封装k3,v3</span></span><br><span class="line">            Text k3 = <span class="keyword">new</span> Text();</span><br><span class="line">            k3.<span class="keyword">set</span>(dt+<span class="string">"\t"</span>+key);</span><br><span class="line">            LongWritable v3 = <span class="keyword">new</span> LongWritable();</span><br><span class="line">            v3.<span class="keyword">set</span>(value);</span><br><span class="line"></span><br><span class="line">            context.write(k3, v3);</span><br><span class="line"></span><br><span class="line">            count++;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>Job的代码实现</p>
<figure class="highlight cos"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line">public <span class="keyword">class</span> DataTopNJob &#123;</span><br><span class="line"></span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        <span class="keyword">if</span>(args.length != <span class="number">2</span>)&#123;</span><br><span class="line">            System.out.println(<span class="string">"参数不足，需要接收HDFS的输入路径和输出路径两个参数"</span>)<span class="comment">;</span></span><br><span class="line">            <span class="comment">//程序退出</span></span><br><span class="line">            System.exit(<span class="number">100</span>)<span class="comment">;</span></span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">// 1. job需要的配置参数</span></span><br><span class="line">            Configuration conf = <span class="keyword">new</span> Configuration()<span class="comment">;</span></span><br><span class="line"></span><br><span class="line">            <span class="comment">// 从输入路径中获取日期</span></span><br><span class="line">            String[] fields = args[<span class="number">0</span>].split(<span class="string">"/"</span>)<span class="comment">;</span></span><br><span class="line">            String tmpdt = fields[fields.length - <span class="number">1</span>]<span class="comment">;</span></span><br><span class="line">            String dt = DateUtils.transDateFormat(tmpdt)<span class="comment">;</span></span><br><span class="line">            conf.<span class="keyword">set</span>(<span class="string">"dt"</span>, dt)<span class="comment">; //向conf中设置日期参数，供reduce阶段获取该参数</span></span><br><span class="line"></span><br><span class="line">            <span class="comment">// 2. 创建一个job</span></span><br><span class="line">            <span class="keyword">Job</span> <span class="keyword">job</span> = <span class="keyword">Job</span>.getInstance(conf)<span class="comment">;</span></span><br><span class="line"></span><br><span class="line">            <span class="comment">// 指定当前类</span></span><br><span class="line">            <span class="comment">// 注意：这一行必须设置，否则在集群中执行时找不到DataStatisJob这个类</span></span><br><span class="line">            <span class="keyword">job</span>.setJarByClass(DataTopNJob.<span class="keyword">class</span>)<span class="comment">;</span></span><br><span class="line"></span><br><span class="line">            <span class="comment">// 3. 指定输入的HDFS路径(可以是文件，也可以是路径)</span></span><br><span class="line">            FileInputFormat.setInputPaths(<span class="keyword">job</span>, <span class="keyword">new</span> Path(args[<span class="number">0</span>]))<span class="comment">;</span></span><br><span class="line">            <span class="comment">// 4. 指定输出的HDFS路径(只能指定一个不存在的目录，如果该目录存在，则程序会报错)</span></span><br><span class="line">            FileOutputFormat.setOutputPath(<span class="keyword">job</span>, <span class="keyword">new</span> Path(args[<span class="number">1</span>]))<span class="comment">;</span></span><br><span class="line"></span><br><span class="line">            <span class="comment">// 5. 指定map相关的代码</span></span><br><span class="line">            <span class="keyword">job</span>.setMapperClass(DataTopNMap.<span class="keyword">class</span>)<span class="comment">;</span></span><br><span class="line">            <span class="comment">// 指定(map的输出)k2的类型</span></span><br><span class="line">            <span class="keyword">job</span>.setMapOutputKeyClass(Text.<span class="keyword">class</span>)<span class="comment">;</span></span><br><span class="line">            <span class="comment">// 指定(map的输出)v2的类型</span></span><br><span class="line">            <span class="keyword">job</span>.setMapOutputValueClass(LongWritable.<span class="keyword">class</span>)<span class="comment">;</span></span><br><span class="line"></span><br><span class="line">            <span class="comment">// 6. 指定reduce相关的代码</span></span><br><span class="line">            <span class="keyword">job</span>.setReducerClass(DataTopNReduce.<span class="keyword">class</span>)<span class="comment">;</span></span><br><span class="line">            <span class="keyword">job</span>.setOutputKeyClass(Text.<span class="keyword">class</span>)<span class="comment">;</span></span><br><span class="line">            <span class="keyword">job</span>.setOutputValueClass(LongWritable.<span class="keyword">class</span>)<span class="comment">;</span></span><br><span class="line"></span><br><span class="line">            <span class="comment">// 7. 提交job</span></span><br><span class="line">            <span class="keyword">job</span>.waitForCompletion(true)<span class="comment">;</span></span><br><span class="line"></span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace()<span class="comment">;</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
</ol>
<h2 id="任务定时shell脚本封装"><a href="#任务定时shell脚本封装" class="headerlink" title="任务定时shell脚本封装"></a>任务定时shell脚本封装</h2><ol>
<li>上述已经完成三个任务的编写，但后两个数据统计任务都依赖与数据清洗任务。所以把任务提交命令进行封装，方便使用，便于定时任务调度。 代码如下：</li>
</ol>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#!/bin/bash</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 判断用户是否输入日期参数，如果未输入，则默认获取昨天日期</span></span><br><span class="line"><span class="comment"># $1为用户输入参数</span></span><br><span class="line"><span class="keyword">if</span> [ <span class="string">"X<span class="variable">$1</span>"</span> = <span class="string">"X"</span> ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">    yes_time=`date +%y%m%d --date=<span class="string">"1 days ago"</span>`</span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">    yes_time=<span class="variable">$1</span></span><br><span class="line"><span class="keyword">fi</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 输入输出目录</span></span><br><span class="line">cleanjob_input=hdfs://hadoop000:9000/data/videoinfo/<span class="variable">$&#123;yes_time&#125;</span></span><br><span class="line">cleanjob_output=hdfs://hadoop000:9000/data/videoinfo_clean/<span class="variable">$&#123;yes_time&#125;</span></span><br><span class="line"></span><br><span class="line">datastatis_input=<span class="variable">$&#123;cleanjob_output&#125;</span></span><br><span class="line">datastatis_output=hdfs://hadoop000:9000/res/datastatisjob/<span class="variable">$&#123;yes_time&#125;</span></span><br><span class="line"></span><br><span class="line">datatopn_input=<span class="variable">$&#123;cleanjob_output&#125;</span></span><br><span class="line">datatopn_output=hdfs://hadoop000:9000/res/datatopnjob/<span class="variable">$&#123;yes_time&#125;</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># jar的目录</span></span><br><span class="line">jobs_home=/data/soft/<span class="built_in">jobs</span></span><br><span class="line"><span class="comment"># jar包名称</span></span><br><span class="line">jobs_jar=hadoop3.0-step-by-step-1.0-SNAPSHOT-jar-with-dependencies.jar</span><br><span class="line"></span><br><span class="line"><span class="comment"># 删除输出目录，为了兼容脚本重复执行的情况</span></span><br><span class="line">hdfs dfs -rm -r <span class="variable">$&#123;cleanjob_output&#125;</span></span><br><span class="line">hdfs dfs -rm -r <span class="variable">$&#123;datastatis_output&#125;</span></span><br><span class="line">hdfs dfs -rm -r <span class="variable">$&#123;datatopn_output&#125;</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 执行数据清洗任务 \ 表示该行未结束</span></span><br><span class="line">hadoop jar <span class="variable">$&#123;jobs_home&#125;</span>/<span class="variable">$&#123;jobs_jar&#125;</span> \</span><br><span class="line">com.aiolos.dataClean.DataCleanJob \</span><br><span class="line"><span class="variable">$&#123;cleanjob_input&#125;</span> <span class="variable">$&#123;cleanjob_output&#125;</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 判断数据清洗任务是否执行成功：通过输出目录下的_SUCCESS文件来判断</span></span><br><span class="line">hdfs dfs -ls <span class="variable">$&#123;cleanjob_output&#125;</span>/_SUCCESS</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> [ <span class="string">"$?"</span> = <span class="string">"0"</span> ] <span class="comment">#$?表示上一条命令的执行结果，0表示获取到</span></span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">    <span class="built_in">echo</span> <span class="string">"cleanjob task execute success..."</span></span><br><span class="line">    <span class="comment"># 执行指标统计任务</span></span><br><span class="line">    hadoop jar <span class="variable">$&#123;jobs_home&#125;</span>/<span class="variable">$&#123;jobs_jar&#125;</span> \</span><br><span class="line">    com.aiolos.dataStatis.DataStatisJob \</span><br><span class="line">    <span class="variable">$&#123;datastatis_input&#125;</span> <span class="variable">$&#123;datastatis_output&#125;</span></span><br><span class="line">    <span class="comment"># 执行统计TopN任务</span></span><br><span class="line">    hadoop jar <span class="variable">$&#123;jobs_home&#125;</span>/<span class="variable">$&#123;jobs_jar&#125;</span> \</span><br><span class="line">    com.aiolos.dataTopN.DataTopNJob \</span><br><span class="line">    <span class="variable">$&#123;datatopn_input&#125;</span> <span class="variable">$&#123;datatopn_output&#125;</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">    <span class="built_in">echo</span> <span class="string">"cleanjob task execute failed... date is <span class="variable">$&#123;yes_time&#125;</span>"</span></span><br><span class="line">    <span class="comment"># 如果失败，则给管理员发短信。可以调用接口或者脚本发送短信</span></span><br><span class="line"><span class="keyword">fi</span></span><br></pre></td></tr></table></figure>

<ol start="2">
<li><p>在主节点中执行上述脚本<br><img src="/blog/images/20191228063315996.jpg" alt="执行上述脚本"></p>
</li>
<li><p>查看执行结果<br><img src="/blog/images/20191228063432472.jpg" alt="执行上述脚本"></p>
</li>
<li><p>查找null出现的原因</p>
<blockquote>
<p>上述最终结果中存在null，则查看数据清洗完成的数据中是否有null，如果有，则看数据清洗之前的数据中是否有null，如果数据清洗之前也有，则查看原始数据中是否有，最终发现是原始数据中就有null，则调整数据清洗代码，修复此问题</p>
</blockquote>
</li>
</ol>
<p><img src="/blog/images/20191228063942962.jpg" alt="查找null出现的原因"></p>
<ol start="5">
<li>编写定时任务<figure class="highlight awk"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 需要把下面这行命令添加到crontab中： vi /etc/crontab</span></span><br><span class="line"><span class="comment"># 每天00:30执行，并将执行日志重定向输出到</span></span><br><span class="line"><span class="number">30</span> <span class="number">00</span> * * * root <span class="regexp">/bin/</span>sh <span class="regexp">/data/</span>soft<span class="regexp">/jobs/</span>data_clean.sh &gt;&gt; <span class="regexp">/data/</span>soft<span class="regexp">/jobs/</span>data_clean.log</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p><img src="/blog/images/20191228064921404.jpg" alt="编写定时任务"></p>
<ol start="6">
<li>可以在shell脚本中增加——针对上述任务执行结果进行检测，如果执行失败，则重试任务，同时发送告警信息</li>
</ol>
<h2 id="使用Sqoop将结果导出到MySQL"><a href="#使用Sqoop将结果导出到MySQL" class="headerlink" title="使用Sqoop将结果导出到MySQL"></a>使用Sqoop将结果导出到MySQL</h2><blockquote>
<p>Apache Sqoop(TM) is a tool designed for efficiently transferring bulk data between Apache Hadoop and structured datastores such as relational databases.</p>
</blockquote>
<p><strong>Sqoop的底层是由MapReduce开发实现的。</strong></p>
<h3 id="快速安装Sqoop工具"><a href="#快速安装Sqoop工具" class="headerlink" title="快速安装Sqoop工具"></a>快速安装Sqoop工具</h3><blockquote>
<p>官网下载地址： <a href="https://www-us.apache.org/dist/sqoop/1.4.7/" target="_blank" rel="noopener">https://www-us.apache.org/dist/sqoop/1.4.7/</a></p>
</blockquote>
<ol>
<li><p>下载Sqoop安装包sqoop-1.4.7.bin__hadoop-2.6.0.tar.gz 到主节点中并解压</p>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">tar</span> <span class="selector-tag">-zxvf</span> <span class="selector-tag">sqoop-1</span><span class="selector-class">.4</span><span class="selector-class">.7</span><span class="selector-class">.bin__hadoop-2</span><span class="selector-class">.6</span><span class="selector-class">.0</span><span class="selector-class">.tar</span><span class="selector-class">.gz</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>重命名${SQOOP_HOME}/conf/sqoop-env-template.sh为sqoop-env.sh</p>
<blockquote>
<p>只要在/etc/profile中配置过HADOOP_HOME，sqoop就可以找到hadoop</p>
</blockquote>
</li>
<li><p>建议配置SQOOP环境变量</p>
<figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">vi /etc/profile</span><br><span class="line"><span class="builtin-name">export</span> <span class="attribute">SQOOP_HOME</span>=/home/soft/sqoop的解压目录</span><br><span class="line"><span class="comment"># 在PATH环境变量中增加$SQOOP_HOME/bin</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>增加mysql数据库驱动jar包(mysql-connector-java-8.0.16.jar)，添加到SQOOP_HOME的lib目录下</p>
</li>
<li><p>创建开放mysql远程访问的账号root和权限[开发权限以后集群中的机器才可以连接windows上的mysql服务]</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">USE</span> mysql;</span><br><span class="line"><span class="keyword">CREATE</span> <span class="keyword">USER</span> <span class="string">'root'</span>@<span class="string">'%'</span> <span class="keyword">IDENTIFIED</span> <span class="keyword">BY</span> <span class="string">'你的密码'</span>;</span><br><span class="line"><span class="keyword">GRANT</span> <span class="keyword">ALL</span> <span class="keyword">ON</span> *.* <span class="keyword">TO</span> <span class="string">'root'</span>@<span class="string">'%'</span>;</span><br><span class="line"><span class="keyword">ALTER</span> <span class="keyword">USER</span> <span class="string">'root'</span>@<span class="string">'%'</span> <span class="keyword">IDENTIFIED</span> <span class="keyword">WITH</span> mysql_native_passowrd <span class="keyword">BY</span> <span class="string">'你的密码'</span>;</span><br><span class="line"><span class="keyword">FLUSH</span> <span class="keyword">PRIVILEGES</span>;</span><br></pre></td></tr></table></figure>
</li>
<li><p>使用Hadoop-3.2版本时，需要在SQOOP_HOME的lib目录下增加common-lang.jar包(commons-lang-2.6.jar)</p>
</li>
<li><p>在mysql中创建数据库，名称为data，创建表top10</p>
<figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">CREATE DATABASE data<span class="built_in"> DEFAULT </span>CHARACTER <span class="builtin-name">SET</span> = utf8<span class="built_in"> DEFAULT </span>COLLATE = utf8_general_ci;</span><br><span class="line">USE DATA;</span><br><span class="line">-- 注意数据表中的字段顺序须与Hadoop输出文件在的字段顺序一致</span><br><span class="line">CREATE TABLE top10 (</span><br><span class="line">	dt date,</span><br><span class="line">	uid varchar(255),</span><br><span class="line">	length bigint(20))</span><br></pre></td></tr></table></figure>

</li>
</ol>
<h3 id="数据导出功能开发，使用Sqoop将MapReduce数据"><a href="#数据导出功能开发，使用Sqoop将MapReduce数据" class="headerlink" title="数据导出功能开发，使用Sqoop将MapReduce数据"></a>数据导出功能开发，使用Sqoop将MapReduce数据</h3><blockquote>
<p>使用sqoop将hdfs中指定目录的数据导出到mysql的表中,代码如下(该段代码也可以放入到data_clean.sh的脚本中)</p>
</blockquote>
<figure class="highlight jboss-cli"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">sqoop export \</span><br><span class="line"><span class="params">--connect</span> jdbc<span class="function">:mysql</span>:<span class="string">//192.168.1.1</span><span class="function">:3306</span>/data?serverTimezone=UTC \</span><br><span class="line"><span class="params">--username</span> root \</span><br><span class="line"><span class="params">--password</span> admin \</span><br><span class="line"><span class="params">--table</span> top10 \</span><br><span class="line"><span class="params">--export-dir</span> <span class="string">/res/videoinfojobtop10/20190821</span> \</span><br><span class="line"><span class="params">--input-fields-terminated-by</span> <span class="string">"\t"</span></span><br></pre></td></tr></table></figure>

<p>完整的执行过程如下图：<br><img src="/blog/images/20191229062356022.jpg" alt="完整的执行过程"></p>
<h2 id="Web项目展示结果"><a href="#Web项目展示结果" class="headerlink" title="Web项目展示结果"></a>Web项目展示结果</h2><p>将数据导出到mysql数据库之后，就可以展示到Web页面中，本节内容略。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/Hadoop3-0入门/" rel="tag"># Hadoop3.0入门</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2019/12/25/java-interview-offer-5/" rel="next" title="【五】剑指Java面试Offer直通车-数据库相关">
                <i class="fa fa-chevron-left"></i> 【五】剑指Java面试Offer直通车-数据库相关
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2019/12/27/java-interview-offer-6/" rel="prev" title="【六】剑指Java面试Offer直通车-Java多线程与并发及其原理">
                【六】剑指Java面试Offer直通车-Java多线程与并发及其原理 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">aiolos</p>
              <p class="site-description motion-element" itemprop="description">Java Spring Hadoop 机器学习</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">126</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">33</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#案例需求分析"><span class="nav-number">1.</span> <span class="nav-text">案例需求分析</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#原始数据清洗代码实现"><span class="nav-number">2.</span> <span class="nav-text">原始数据清洗代码实现</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#数据统计代码实现–基于主播维度的四个指标"><span class="nav-number">3.</span> <span class="nav-text">数据统计代码实现–基于主播维度的四个指标</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#数据统计代码实现–基于主播的TOPN计算"><span class="nav-number">4.</span> <span class="nav-text">数据统计代码实现–基于主播的TOPN计算</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#任务定时shell脚本封装"><span class="nav-number">5.</span> <span class="nav-text">任务定时shell脚本封装</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#使用Sqoop将结果导出到MySQL"><span class="nav-number">6.</span> <span class="nav-text">使用Sqoop将结果导出到MySQL</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#快速安装Sqoop工具"><span class="nav-number">6.1.</span> <span class="nav-text">快速安装Sqoop工具</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#数据导出功能开发，使用Sqoop将MapReduce数据"><span class="nav-number">6.2.</span> <span class="nav-text">数据导出功能开发，使用Sqoop将MapReduce数据</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Web项目展示结果"><span class="nav-number">7.</span> <span class="nav-text">Web项目展示结果</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">aiolos</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
